package com.cx.ctrl;

import com.cx.common.restful.BaseResult;
import com.cx.po.SysUser;
import com.cx.po.SysUserRole;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * Author:CHENXIAOYI
 * Since:2020/12/25 9:12
 */
@RestController
public class HelloCtrl {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private PasswordEncoder passwordEncoder;

    @GetMapping("/hello")
    public BaseResult<Object> hello(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication instanceof UsernamePasswordAuthenticationToken){
            return BaseResult.success(authentication.getPrincipal());
        }
            return BaseResult.error();
    }

    @GetMapping("/user/regist")
    public BaseResult<?> regist(){
        SysUser sysUser = new SysUser();
        sysUser.setId(1L);
        sysUser.setUsername("cxy");
        sysUser.setPassword(passwordEncoder.encode("123456"));
        sysUser.setSex(1);
        mongoTemplate.save(sysUser);
        mongoTemplate.save(SysUserRole.builder().id(1L).userId(1L).roleId(1L).build());
        mongoTemplate.save(SysUserRole.builder().id(2L).userId(1L).roleId(2L).build());
        SysUser sysUser1 = new SysUser();
        sysUser1.setId(2L);
        sysUser1.setUsername("cs");
        sysUser1.setPassword(passwordEncoder.encode("123456"));
        sysUser1.setSex(0);
        mongoTemplate.save(sysUser1);
        mongoTemplate.save(SysUserRole.builder().id(3L).userId(2L).roleId(2L).build());

        return BaseResult.success();
    }

}
